package cn.com.wdjedu.androidapp.wjeduandroid.ui.baseui;

import android.annotation.TargetApi;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import java.util.List;

import cn.com.wdjedu.androidapp.wjeduandroid.R;
import cn.com.wdjedu.androidapp.wjeduandroid.db.WJEdudb;
import cn.com.wdjedu.androidapp.wjeduandroid.support.lib.mvputils.BasePresenter;
import cn.com.wdjedu.androidapp.wjeduandroid.support.lib.pulltorefresh.PullToRefreshBase;
import cn.com.wdjedu.androidapp.wjeduandroid.support.lib.view.MyGridView;
import nl.nl2312.rxcupboard.RxCupboard;
import nl.nl2312.rxcupboard.RxDatabase;

/**
 * 封装gridview的Fragment
 */

public abstract class GridViewFragment<T,P extends BasePresenter> extends AbstractAppFragment {


    public MyGridView mPullToRefreshListView;
    public TextView mEmpty;
    public ProgressBar mProgressBar;

    public abstract List<T> getList();

    public List<T> lists;

    public BaseAdapter listAdapter;

    protected View footerView;

    public View getRoot() {
        return root;
    }

    protected View root;

    protected P mvpPresenter;
    private SQLiteDatabase db ;
    public RxDatabase rxCupboard ;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.mvpPresenter = createPresenter();
        root = inflater.inflate(R.layout.gridview_layout, container, false);
        buildLayout(inflater, root);
        return root;
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void buildLayout(LayoutInflater inflater, View root) {
        mPullToRefreshListView = (MyGridView) root.findViewById(R.id.listView);
        mEmpty = (TextView) root.findViewById(R.id.empty);
        mProgressBar = (ProgressBar) root.findViewById(R.id.progressbar);


        footerView = inflater.inflate(R.layout.listview_footer_layout, null);
        dismissFooterView();
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void dismissFooterView() {
        final View progressbar = footerView.findViewById(R.id.loading_progressbar);
        progressbar.animate().scaleX(0).scaleY(0).alpha(0.5f).setDuration(300)
                .withEndAction(new Runnable() {
                    @Override
                    public void run() {
                        progressbar.setVisibility(View.GONE);
                    }
                });
        footerView.findViewById(R.id.laod_failed).setVisibility(View.GONE);
    }

    public BaseAdapter getListAdapter() {
        return listAdapter;
    }


    /**
     * 创建Adapter
     */
    protected abstract BaseAdapter buildListAdapter();

    /**
     * 刷新布局
     *
     * @param bean
     */
    protected void refreshLayout(List<T> bean) {
        if (bean != null && bean.size() > 0) {
            mEmpty.setVisibility(View.INVISIBLE);
            mProgressBar.setVisibility(View.INVISIBLE);
            mPullToRefreshListView.setVisibility(View.VISIBLE);
        } else if (bean == null || bean.size() == 0) {
            mEmpty.setVisibility(View.VISIBLE);
            mProgressBar.setVisibility(View.INVISIBLE);
            mPullToRefreshListView.setVisibility(View.INVISIBLE);
        } else {
            mEmpty.setVisibility(View.INVISIBLE);
            mProgressBar.setVisibility(View.INVISIBLE);
            mPullToRefreshListView.setVisibility(View.VISIBLE);

        }
    }

    /**
     * 各种监听器
     */
    private PullToRefreshBase.OnRefreshListener<ListView> listViewOnRefreshListener
            = new PullToRefreshBase.OnRefreshListener<ListView>() {
        @Override
        public void onRefresh(PullToRefreshBase<ListView> refreshView) {
            if (getActivity() == null) {
                return;
            }
//            getPullToRefreshListView().setRefreshing(true);
            getListAdapter().notifyDataSetChanged();
        }
    };
    private PullToRefreshBase.OnLastItemVisibleListener listViewOnLastItemVisibleListener
            = new PullToRefreshBase.OnLastItemVisibleListener() {
        @Override
        public void onLastItemVisible() {
            if (getActivity() == null) {
                return;
            }

        }
    };

    private AbsListView.OnScrollListener listViewOnScrollListener
            = new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            switch (scrollState) {
                case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:

                    break;
                case AbsListView.OnScrollListener.SCROLL_STATE_FLING:

                    break;
                case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:

                    break;
            }
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                             int totalItemCount) {
        }
    };


    private AdapterView.OnItemClickListener listViewOnItemClickListener
            = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            listViewItemClick(parent, view, position, id);
        }


    };

    /**
     * 另起一个listview item的监听器
     *
     * @param parent
     * @param view
     * @param position
     * @param id
     */
    protected abstract void listViewItemClick(AdapterView parent, View view, int position, long id);


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mPullToRefreshListView.setOnScrollListener(listViewOnScrollListener);
        mPullToRefreshListView.setOnItemClickListener(listViewOnItemClickListener);
//        mPullToRefreshListView.setOnPullEventListener(getPullEventListener());
        listAdapter = buildListAdapter();
        mPullToRefreshListView.setAdapter(listAdapter);
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        this.mvpPresenter = createPresenter();
        if (db==null)
            db = WJEdudb.getConnection(getActivity());
        if (rxCupboard==null)
            rxCupboard = RxCupboard.withDefault(db);
        super.onCreate(savedInstanceState);
    }

    protected abstract P createPresenter();

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (mvpPresenter != null){
            mvpPresenter.dettach();
        }
    }

    /** Fragment当前状态是否可见 */
    protected boolean isVisible;


    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if(getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInvisible();
        }
    }


    /**
     * 可见
     */
    protected void onVisible() {
//        lazyLoad();
    }


    /**
     * 不可见
     */
    protected void onInvisible() {


    }

    @Override
    public void onDestroyView() {
//        Datamanage.getInstance().getImageLoader(this.getActivity()).clearMemoryCache();
//        Datamanage.getInstance().getImageLoader(this.getActivity()).clearDiskCache();
        super.onDestroyView();
    }

    /**
     * 延迟加载
     * 子类必须重写此方法
     */
//    protected abstract void lazyLoad();

}
